<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['basic:level:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      border
      stripe
      :data="levelList"
      :span-method="spanMethod"
    >
      <el-table-column prop="countryName" label="所属国家" width="120" />
      <el-table-column prop="level" label="家长引导" width="120" />
      <el-table-column prop="levelZh" label="家长引导中文" width="120" />
      <el-table-column prop="description" label="引导模板" align="left" />
      <el-table-column prop="status" label="类型状态" width="100">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="130">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['basic:level:edit']">编辑</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['basic:level:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分级对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="国家/地区" prop="countryId">
          <el-select v-model="form.countryId" placeholder="请选择语言所属国家/地区" clearable style="width: 100%">
            <el-option
              v-for="item in countryOptions"
              :key="item.countryId"
              :label="item.name"
              :value="item.countryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="家长引导" prop="level">
          <el-input v-model="form.level" placeholder="请输入家长引导等级" />
        </el-form-item>
        <el-form-item label="引导中文" prop="levelZh">
          <el-input v-model="form.levelZh" placeholder="请输入家长引导中文等级" />
        </el-form-item>
        <el-form-item label="类型状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="引导模板" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            maxlength="100"
            show-word-limit
            placeholder="例：本片在${country}的评级为【${level}】，适合任何年龄观看。"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import { listLevel, getLevel, delLevel, addLevel, updateLevel } from "@/api/basic/level";
import { listCountry } from "@/api/basic/country";
import { getCurrentInstance, ref, reactive, toRefs } from 'vue';

const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict('sys_normal_disable');

const levelList = ref([]);
const countryOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    level: [
      { required: true, message: "请输入家长引导等级", trigger: "blur" },
      { min: 1, max: 16, message: "长度在 1 到 16 个字符", trigger: "blur" }
    ],
    levelZh: [
      { max: 32, message: "长度不能超过 32 个字符", trigger: "blur" }
    ],
    countryId: [
      { required: true, message: "请选择国家", trigger: "change" }
    ],
    description: [
      { required: true, trigger: "blur" },
      { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询分级列表 */
function getList() {
  loading.value = true;
  listLevel(queryParams.value).then(response => {
    levelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询国家列表 */
function getCountryList() {
  listCountry().then(response => {
    countryOptions.value = response.rows || [];
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    levelId: null,
    countryId: null,
    level: null,
    levelZh: null,
    status: null,
    description: null
  };
  proxy.resetForm("levelRef");
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getCountryList();
  open.value = true;
  title.value = "添加家长引导";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getCountryList();
  const _levelId = row.levelId;
  const item = levelList.value.find(value => value.levelId === _levelId);
  form.value = { ...item };
  open.value = true;
  title.value = "修改家长引导";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs.levelRef.validate((valid) => {
    if (valid) {
      if (form.value.levelId) {
        updateLevel(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLevel(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _levelId = row.levelId;
  proxy.$modal.confirm('是否确认删除"' + _levelId + '"的数据项？').then(async () => {
    await delLevel(_levelId);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  });
}

/** 表格合并行方法 */
function spanMethod({ row, column, rowIndex, columnIndex }) {
  if (columnIndex === 0) {
    // 当当前行与上一行内容相同时 返回0 0 意味消除
    if (rowIndex > 0 && row.countryId === levelList.value[rowIndex - 1].countryId) {
      return {
        rowspan: 0,
        colspan: 0
      };
    } else {
      let rows = 1;
      for (let i = rowIndex; i < levelList.value.length - 1; i++) {
        if (row.countryId === levelList.value[i + 1].countryId) {
          rows++;
        }
      }
      // 返回相同内容的行数
      return {
        rowspan: rows,
        colspan: 1
      };
    }
  }
}

getList();
</script>